
from dvadmin.system.models import App,Users,Role
from dvadmin.utils.serializers import CustomModelSerializer
from dvadmin.utils.viewset import CustomModelViewSet
from rest_framework.decorators import action
from rest_framework import serializers
from dvadmin.utils.json_response import SuccessResponse, ErrorResponse, DetailResponse
from django.core.cache import cache



class AppRoleSerializer(CustomModelSerializer):
    """
    用户应用权限
    """

    class Meta:
        model = Role
        read_only_fields = ["id"]
        fields = ('label', 'key','id','value')


class AppSerializer(CustomModelSerializer):
    """
    区块-序列化器
    """
    class Meta:
        model = App
        fields = "__all__"
        read_only_fields = ["id"]

class abcNewWebRouterSerializer(CustomModelSerializer):
    """
    前端菜单路由的简单序列化器
    """
    value = serializers.IntegerField(source="id")
    label = serializers.CharField(source="appName")

    class Meta:
        model = App
        fields = '__all__'
        fields = ('label', 'value','appName')
        # 'component_name', 'cache', 'visible', 'menuPermission','schema')
        # read_only_fields = ["id"]

class AppViewSet(CustomModelViewSet):
    """
    list:查询
    create:新增
    update:修改
    retrieve:单例
    destroy:删除
    """
    queryset = App.objects.all()

    serializer_class = AppSerializer
    # extra_filter_backends = []

    # @action(methods=['GET'], detail=False, permission_classes=[])

    def list(self, request, *args, **kwargs):
        if self.request.user.is_superuser:
            queryset = self.filter_queryset(self.get_queryset())
            page = self.paginate_queryset(queryset)
            if page is not None:
                serializer = self.get_serializer(page, many=True, request=request)
                return self.get_paginated_response(serializer.data)
            serializer = self.get_serializer(queryset, many=True, request=request)
            return SuccessResponse(data=serializer.data, msg="获取成功")
        else:
            a = Users.objects.get(id = self.request.user.id)
            applist = []
            for k in a.role.all():
                data = k.app.values_list("id")
                if data:
                    for i in data:
                        applist.append(i[0])
            queryset = self.queryset.filter(id__in=set(applist))
            serializer = self.get_serializer(queryset, many=True, request=request)
            return SuccessResponse(data=serializer.data, msg="获取成功")


    @action(methods=['GET'], detail=False,permission_classes=[])
    def choice(self, request):
        """用于前端菜单树结构树"""
        if self.request.user.is_superuser:
            serializer = abcNewWebRouterSerializer(self.queryset.all(), many=True, request=request)
            data = serializer.data
            return SuccessResponse(data=data, msg="获取成功")
        else:
            a = Users.objects.get(id=self.request.user.id)
            applist = []
            for k in a.role.all():
                data = k.app.values_list("id")
                if data:
                    for i in data:
                        applist.append(i[0])
            queryset = self.queryset.filter(id__in=set(applist))
            serializer = abcNewWebRouterSerializer(queryset, many=True, request=request)
            return SuccessResponse(data=serializer.data, msg="获取成功")



    @action(methods=['GET'], detail=False, permission_classes=[])
    def getpathdata(self,request,*args, **kwargs):
        """根据路径获取数据"""
        appPath = request.query_params['appPath']
        cacheName ="{}_{}".format('appName',appPath)
        cachedata = cache.get(cacheName)
        if cachedata:
            return DetailResponse(data=cachedata, msg="成功")
        queryset = self.queryset.filter(appPath=appPath).first()
        if not queryset:
            queryset = self.queryset.filter(appPath="/").first()
        serializer = AppSerializer(queryset, many=False)
        cache.set(cacheName,serializer.data,timeout=60)
        return DetailResponse(data=serializer.data,msg="成功")
